import json

from django import http
from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django.views import View

from areas import contanst
from areas.models import Area
from response_code import RETCODE


class AreaView(View):
    """省市区三级联动"""

    def get(self, request):
        area_id = request.GET.get("area_id")
        if not area_id:
            # 先查缓存
            province_list = cache.get(contanst.PROVINCES_CACHE_KEY)
            if not province_list:
                try:
                    # 查询省份
                    provinces_model = Area.objects.filter(parent__isnull=True)
                    province_list = []
                    for m in provinces_model:
                        province_list.append({
                            "id": m.id,
                            "name": m.name
                        })
                    # 把数据存进缓存
                    cache.set(contanst.PROVINCES_CACHE_KEY, province_list, contanst.EXPIRES)
                except Exception as e:
                    print(e)
                    return http.JsonResponse({"code": RETCODE.DBERR, "err_msg": "获取省份数据失败"})
            return http.JsonResponse({"code": RETCODE.OK, "province_list": province_list})
        else:
            # 先查缓存
            sub_data = cache.get('%s_%s' % (contanst.SUBS_CACHE_KEY, area_id))
            if not sub_data:
                # 查询城市
                # 先查所在的省份
                try:
                    parent_model = Area.objects.get(id=area_id)
                    # city_model = Area.objects.filter(parent_id=area_id)
                    city_model = parent_model.subs.all()
                    sub_data = {
                        "id": parent_model.id,
                        "name": parent_model.name,
                        "subs": []
                    }

                    for m in city_model:
                        sub_data["subs"].append({
                            "id": m.id,
                            "name": m.name
                        })
                    # 存缓存
                    cache.set('%s_%s' % (contanst.SUBS_CACHE_KEY, area_id), sub_data, contanst.EXPIRES)
                except Exception as e:
                    print(e)
                    return http.JsonResponse({"code": RETCODE.DBERR, "err_msg": "获取城市数据失败"})
            return http.JsonResponse({"code": RETCODE.OK, "sub_data": sub_data})



